package com.yh.jandan.ext.thread;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;

import com.jfinal.kit.JsonKit;
import com.yh.jandan.model.Meizi;
import com.yh.jandan.util.DateUtils;

public class MeiziSaveThread {
	
	static ConcurrentLinkedQueue < Meizi > mzs = new ConcurrentLinkedQueue < Meizi > ( );
	static boolean isRuning = false;
	
	public static void hold ( Meizi meizi ) {
		mzs.add ( meizi );
	}
	
	public static int getCurrentLength ( ) {
		return mzs.size ( );
	}
	
	public static void stop ( ) {
		isRuning = false;
	}
	
	public static void start ( ) {
		
		if ( isRuning ) return;
		isRuning = true;
		
		init ( );
		
		new Thread ( new Runnable ( ) {
			public void run ( ) {
				while ( isRuning ) {
					sleep_seconds ( 1 );
					if ( mzs.isEmpty ( ) ) {
						continue;
					}
					Meizi meizi = mzs.poll ( );
					if ( null == meizi ) continue;
					save_one ( meizi );
					MeiziCheckThread.hold ( meizi ); // 去检查下
				}
			}
		} ).start ( );
		
	}
	
	private static void init ( ) {
		if ( null != mzs ) return;
		mzs = new ConcurrentLinkedQueue < Meizi > ( );
	}
	
	private static void save_one ( Meizi meizi ) {
		try {
			meizi.save ( );
			write_log ( "save():[" + new Date ( ) + "]" + JsonKit.toJson ( meizi ) );
		} catch ( Exception e ) {
			e.printStackTrace ( );
		}
	}
	
	private static void sleep_seconds ( long i ) {
		try {
			TimeUnit.SECONDS.sleep ( i );
		} catch ( InterruptedException e ) {
			e.printStackTrace ( );
		}
		
	}
	
	private static void write_log ( String string ) {
		try {
			System.out.println ( string );
			FileUtils.write ( new File ( getLogFile ( ) ) , string + "\n" , true );
		} catch ( IOException e ) {
			e.printStackTrace ( );
		}
	}
	
	private static String getLogFile ( ) {
		String datestr = DateUtils.getDateByFormat ( DateUtils.YMD_FORMAT );
		return log_file.replace ( "{date}" , datestr );
	}
	
	static String log_file = "logs/MeiziSaveThread-{date}.log";
	
}
